<template>
	<view>
		<!-- 顶部位置信息 -->
		<view class="head_">
			<view style="display: flex;width: 500rpx;align-items: center;" @click="changeShop">
				<wd-icon name="refresh1" size="20px"></wd-icon>
				<text class="line1">{{venueName || ""}}</text>
			</view>
			<view style="font-size: 24rpx;color: #333;" @click="toOrderRecord">
				我的订单
			</view>
		</view>
		<!-- 主体内容区域 -->
		<view class="wraper">
			<!-- 左侧分类导航 -->
			<wd-sidebar v-model="active" @change="handleChange">
				<wd-sidebar-item 
					v-for="(item, index) in categories" 
					:key="index" 
					:value="index" 
					:label="item.title" 
					:badge="item.num"
				/>
			</wd-sidebar>
			
			<!-- 右侧商品列表 -->
			<scroll-view 
				class="content" 
				scroll-y 
				scroll-with-animation 
				:scroll-top="scrollTop" 
				:throttle="false" 
				@scroll="onScroll"
			>
			 <!-- 暂无内容 -->
		 		<wd-status-tip v-if="categories?.length == 0" style="margin-top: 200rpx;" image="/static/viewNull.png"  :image-size="{ height: 50,  width: 50}" tip="暂无商品" />
				<view v-for="(category, categoryIndex) in categories" :key="categoryIndex" class="category">
					<!-- 分类标题 -->
					<view class="category-title">{{ category.title }}</view>
					
					<!-- 商品列表 -->
					<view class="goods-list">
						<view 
							v-for="(item, itemIndex) in category.goodsRespList" 
							:key="itemIndex" 
							class="goods-item"
							@click="goToDetail(item)"
						>
							<!-- 商品图片 -->
							<image 
								:src="item.cover || '/static/img/bg1.png'" 
								class="goods-image" 
								mode="aspectFill"
							></image>
							
							<!-- 商品信息 -->
							<view class="goods-info" >
								<text class="goods-name">{{ item.title || '' }}</text>
								<text class="goods-desc">{{ item.englishTitle || '' }}</text>
								
								<!-- 价格和操作区域 -->
								<view class="goods-bottom" >
									<view class="price-box" >
										<text class="price-symbol">¥</text>
										<text class="price">{{ item.price || '' }}</text>
									</view>
									
									<!-- 购物车操作按钮 -->
									<view class="cart-controls"> 
										<!-- 如果商品已加入购物车，显示徽标数量 v-if="getItemCount(categoryIndex, itemIndex) > 0" -->
										<view  class="badge-wrapper">
										<!-- 	<wd-badge :model-value="item.virtualSaleNum">
											</wd-badge> -->
											<wd-icon name="add" size="20px" color="#000000" ></wd-icon>
										</view>
										
										<!-- 如果商品未加入购物车，显示加号图标，点击跳转到详情页 -->
									<!-- 	<view v-else class="add-icon-wrapper" @click="goToDetail(categoryIndex, itemIndex)">
											<wd-icon name="add" size="20px" color="#000000"></wd-icon>
										</view> -->
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
				
				<!-- 底部安全距离 -->
				<view class="bottom-safe-area"></view>
			</scroll-view>
		</view>
		
		<!-- 购物车组件 -->
		<water-cart 
			ref="cartRef"
			:cart-data="cartData"
			@update-cart="handleUpdateCart"
		/>
		<fui-loading type="col" v-if="loadActive" :isFixed="true" :isMask="true"></fui-loading>
	</view>
</template>

<script setup>
	import waterCart from './components/cat.vue' // 购物车组件
	import { getRect, isArray } from '@/uni_modules/wot-design-uni/components/common/util'
	// 响应式数据
	const active = ref(0) // 当前激活的分类索引
	const scrollTop = ref(0) // 滚动位置
	const itemScrollTop = ref([]) // 各分类的滚动位置
	const cartRef = ref(null) // 购物车组件引用
	const venueName = ref(null) // 购物车组件引用
	const businessId = ref(null) // 商家ID
	const loadActive = ref(false) // 加载中状态
	// 购物车数据
	const cartData = ref({
		detailList: [], // 购物车商品列表
		goodsNum: 0, // 总数量
		totalAmount: 0 ,// 总价格
		venueId: null ,// 商家ID
		venueName: null // 商家名称
	})

	// 分类数据
	const categories = ref([])
	const setBusinessId = (e)=>{
		console.log(e);
	}
	/**
	 * 增加商品到购物车
	 * @param {number} categoryIndex - 分类索引
	 * @param {number} itemIndex - 商品索引
	 */
	const increaseItem = (categoryIndex, itemIndex) => {
		const item = categories.value[categoryIndex].items[itemIndex]
		const existingItem = cartData.items.find(cartItem => cartItem.id === item.id)
		
	}
	/**
	 * 从购物车减少商品
	 * @param {number} categoryIndex - 分类索引
	 * @param {number} itemIndex - 商品索引
	 */
	const decreaseItem = (categoryIndex, itemIndex) => {
		const item = categories.value[categoryIndex].items[itemIndex]
		const existingItemIndex = cartData.items.findIndex(cartItem => cartItem.id === item.id)
	}

	/**
	 * 处理购物车更新事件
	 * @param {Object} updatedCart - 更新后的购物车数据
	 */
	const handleUpdateCart = (updatedCart) => {
		console.log(updatedCart);
		Object.assign(cartData.value, updatedCart);
	}
	// 我的订单
	const toOrderRecord = () => {
		uni.navigateTo({
			url: `/pagesA/view/waterBar/orderRecord?venueId=${businessId.value}`
		})
	}
	/**
	 * 跳转到商品详情页面
	 */
	const goToDetail = (item) => {
		uni.navigateTo({
			url: `/pagesA/view/waterBar/detail?id=${item.id}`
		})
	}

	/**
	 * 分类切换处理
	 * @param {Object} param - 包含value的对象
	 */
	const handleChange = ({ value }) => {
		active.value = value
		// 滚动到对应分类位置
		const targetScrollTop = (itemScrollTop.value[value]+88) || 0
		scrollTop.value = targetScrollTop
	}

	/**
	 * 滚动事件处理
	 * @param {Object} e - 滚动事件对象
	 */
	const onScroll = (e) => {
		const { scrollTop } = e.detail
		// 如果滚动到顶部，激活第一个分类
		if (scrollTop <= 10) {
			active.value = 0
			return
		}
		
		// 找到当前应该激活的分类
		// 从后往前遍历，找到第一个scrollTop大于等于当前滚动位置的分类
		for (let i = itemScrollTop.value.length - 1; i >= 0; i--) {
			if (scrollTop >= itemScrollTop.value[i] - 60) { // 60rpx的偏移量，考虑分类标题高度
				active.value = i
				break
			}
		}
	}
	// 获取商品数据
	const getGoods = async () => {
		loadActive.value = true
		const res = await uni.api.getWaterGoodsInfo({businessId:businessId.value});
		if (res.code === 0) {
			categories.value = res?.data?.categoryRespList || []
			venueName.value = res?.data?.venueName || '';
			getCart();
			// 延迟获取各分类的滚动位置，确保DOM渲染完成
			nextTick(() => {
				setTimeout(() => {
					getRect('.category', true).then((rects) => {
						if (isArray(rects)) {
							// 计算每个分类相对于scroll-view的位置
							itemScrollTop.value = rects.map((item, index) => {
								// 第一个分类从0开始，其他分类需要减去一定偏移
								return index === 0 ? 0 : (item.top || 0) - 60-(44+44)
							})
							// 初始化时滚动到顶部
							scrollTop.value = 0
						}
					})
					loadActive.value = false;
				}, 100)
			})
		}
	}
	// 更新商品数据
	const upGoods = async () => {
		const res = await uni.api.getWaterGoodsInfo({businessId:businessId.value});
		if (res.code === 0) {
			categories.value = res?.data?.categoryRespList || []
		}
	}
	// 更新购物车
	const getCart = async () => {
		const res = await uni.api.getCarInfo({businessId:businessId.value});
		if (res.code === 0) {
			// 确保购物车数据结构正确
			cartData.value = {
				...res.data,
				venueId:businessId.value,
				venueName:venueName.value
			};
			
		}
	}
	// 切换门店
	const changeShop = ()=>{
		uni.redirectTo({
			url: `/pagesA/view/shopList/index`
		})
	}
	// 组件挂载后初始化
	onLoad((opt) => {
		businessId.value = opt.venueId;
		// 监听购物车数据更新事件
		uni.$on('refreshWaterBarData', () => {
			getCart();
			upGoods();
		});
		getGoods();
	})
	
	// 页面卸载时清理事件监听
	onUnload(() => {
		console.log('卸载refreshWaterBarData');
		
		uni.$off('refreshWaterBarData');
	})
	defineExpose({
		setBusinessId
	})
</script>
<style lang="scss">
	.head_ {
		height: 88rpx;
		background: #fff;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 24rpx;
		box-sizing: border-box;
		.line1 {
			color: #333;
			font-size: 32rpx;
			font-weight: 500;
			padding-left:6rpx;
		}
		
		.search-icon {
			color: #999;
		}
	}

	.wraper {
		display: flex;
		height: calc(100vh - 88rpx);
		.content {
			flex: 1;
			background: #ffffff;
			padding: 0 0 120rpx 0; // 为购物车底部栏留出空间
		}
	}
	.category {
		margin-bottom: 32rpx;
		
		.category-title {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
			padding: 24rpx 24rpx 16rpx;
			background: #ffffff;
			position: sticky;
			top: 0;
			z-index: 10;
			border-bottom: 1px solid #f5f5f5;
		}
	}

	.goods-list {
		padding: 0 24rpx;
		
		.goods-item {
			// background: #fff;
			border-radius: 16rpx;
			margin-bottom: 16rpx;
			padding: 24rpx;
			display: flex;
			align-items: center;
			// box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
			
			.goods-image {
				width: 120rpx;
				height: 120rpx;
				border-radius: 12rpx;
				margin-right: 24rpx;
				background: #f5f5f5;
			}
			
			.goods-info {
				flex: 1;
				
				.goods-name {
					font-size: 32rpx;
					color: #333;
					font-weight: 500;
					display: block;
					margin-bottom: 8rpx;
					line-height: 1.4;
				}
				
				.goods-desc {
					font-size: 24rpx;
					color: #999;
					display: block;
					margin-bottom: 16rpx;
					line-height: 1.3;
				}
				
				.goods-bottom {
					display: flex;
					align-items: center;
					justify-content: space-between;
					
					.price-box {
						display: flex;
						align-items: baseline;
						color: #ff4757;
						font-weight: bold;
						
						.price-symbol {
							font-size: 20rpx;
							margin-right: 4rpx;
						}
						
						.price {
							font-size: 32rpx;
						}
					}
					
					.cart-controls {
						display: flex;
						align-items: center;
						justify-content: center;
						
						.badge-wrapper {
							position: relative;
						}
						
						.add-icon-wrapper {
							display: flex;
							align-items: center;
							justify-content: center;
							width: 44rpx;
							height: 44rpx;
						}
					}
				}
			}
		}
	}

	.bottom-safe-area {
		height: 40rpx;
	}

	:deep(.wd-sidebar){
		width: 160rpx !important;
		background: #fff !important;
	}
	:deep(.wd-sidebar-item){
		padding: 24rpx 16rpx !important;
		font-size: 28rpx !important;
		color: #000 !important;
	}
	:deep(.wd-sidebar-item--active::before){
		background: #000 !important;
		height: 60rpx !important;
	}
</style>